import { useState } from 'react';
import { Table, Typography, Modal, Tabs, Flex, Input, Button } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import data from './output.json';

const { Title, Paragraph } = Typography;
const { TabPane } = Tabs;

type Record = typeof data[0];

interface Action {
	time: string;
	timestamp: number;
	name: string;
	theme: string;
}

interface Information {
	name: string;
	category: string;
	key: number;
	score: number;
	desc: string;
	actions: Action[];
}

// 按贡献主体分类和项目/贡献者名称计数的函数
function countByCategoryAndName(category: string, records: Record[]) {
	const filteredRecords = records.filter(record => record.贡献主体 === category);
	const countMap = new Map<string, Information>();

	filteredRecords.forEach(record => {
		const name = record['项目/贡献者名称'];
		if (!name) return;
		// 检查字符串是否符合"3月5日"的格式
		let dateStr = "";
		let actionDate = record.活动日期 as any;
		let timestamp = 0;
		if (typeof actionDate === 'string') {
			dateStr = actionDate;
			const pattern = /^\d{1,2}月\d{1,2}日$/;
			if (!pattern.test(dateStr)) {
				return;
			}
			// 获取月份和日期
			const [month, day] = dateStr.split('月').map(str => parseInt(str, 10));
			timestamp = new Date(new Date().getFullYear(), month - 1, day).getTime();
		} else if (typeof actionDate === 'number') {
			const date = new Date(actionDate);
			const month = date.getMonth() + 1;
			const day = date.getDate();
			dateStr = `${month}月${day}日`;
			timestamp = actionDate;
		} else {
			return;
		}
		if (countMap.has(name)) {
			const info = countMap.get(name)!;
			info.score += record.积分;
			info.actions.push({
				time: dateStr,
				timestamp,
				name: record.活动归属分类,
				theme: record.贡献详情链接 ?? "",
			});
		} else {
			countMap.set(name, {
				name,
				key: 0,
				category,
				score: record.积分,
				desc: '',
				actions: [
					{
						time: dateStr,
						timestamp,
						name: record.活动归属分类,
						theme: record.贡献详情链接 ?? "",
					},
				],
			});
		}
	});

	// 将Map对象转换为数组，并按记录数排序
	const sortedArray = Array.from(countMap.entries()).sort((a, b) => b[1].score - a[1].score).map(entry => entry[1]);
	sortedArray.forEach((info, index) => {
		info.actions.sort((a, b) => b.timestamp - a.timestamp);
		info.key = index + 1;
		info.desc = `${info.actions[0].time}，参与活动”${info.actions[0].name}“`;
	});
	return sortedArray;
}

// 使用上述函数生成排名
const projectRanking = countByCategoryAndName('项目', data);
const contributorRanking = countByCategoryAndName('贡献者', data);

const App = () => {
	const showModal = (record: Information) => {
		setCurrentInfo(record);
	};
	const projectColumns = [
		{
			title: '排名',
			dataIndex: 'key',
			key: 'key',
		},
		{
			title: '名称',
			dataIndex: 'name',
			key: 'name',
		},
		{
			title: '贡献积分',
			dataIndex: 'score',
			key: 'score',
		},
		{
			title: '最新活动',
			dataIndex: 'desc',
			key: 'desc',
			// eslint-disable-next-line
			render: (text: string, record: Information) => <a href='javascript:void(0)' onClick={() => showModal(record)}>{text}</a>,
		},
	];
	const contributorColumns = [
		{
			title: '排名',
			dataIndex: 'key',
			key: 'key',
		},
		{
			title: '名称',
			dataIndex: 'name',
			key: 'name',
		},
		{
			title: '贡献积分',
			dataIndex: 'score',
			key: 'score',
		},
		{
			title: '最新活动',
			dataIndex: 'desc',
			key: 'desc',
			// eslint-disable-next-line
			render: (text: string, record: Information) => <a href='javascript:void(0)' onClick={() => showModal(record)}>{text}</a>,
		},
	];
	const [searchText, setSearchText] = useState('');
	const [activeTab, setActiveTab] = useState('1');
	const [currentInfo, setCurrentInfo] = useState<Information | null>(null);
	const searchTextLower = searchText.toLowerCase();
	const filteredProjectRanking = projectRanking.filter((project) =>
		project.name.toLowerCase().includes(searchTextLower)
	);
	const filteredContributorRanking = contributorRanking.filter((contributor) =>
		contributor.name.toLowerCase().includes(searchTextLower)
	);
	const [isModalVisible, setIsModalVisible] = useState(false);

	const showReadmeModal = () => {
		setIsModalVisible(true);
	};

	const handleReadmeOk = () => {
		setIsModalVisible(false);
	};

	const handleReadmeCancel = () => {
		setIsModalVisible(false);
	};

	return (
		<Flex gap="middle" vertical style={{paddingLeft: 60, paddingRight: 60}}>
			<Flex><Title level={1}>开放原子开源活动贡献榜</Title><Button type="link" size='large' style={{height: 100}} icon={<QuestionCircleOutlined/>} onClick={showReadmeModal}/></Flex>
			<Modal title="说明" open={isModalVisible} onOk={handleReadmeOk} onCancel={handleReadmeCancel} footer={null}>
				<h2>常见问题解答</h2>
				<ul>
					<li>
						Q: 如何参与排名？<br/>
						A: 参与开放原子开源基金会及旗下项目开源活动。榜单规则详见README：<a href='https://atomgit.com/fenju/open-atom-contributor-leaderboard'>https://atomgit.com/fenju/open-atom-contributor-leaderboard</a>
					</li>
					<li>
						Q: 排名更新频率是多久？<br/>
						A: 我们每周更新一次排名。
					</li>
					<li>
						Q: 贡献记录没有被录入？<br/>
						A: 请到AtomGit仓库提交Issue：<a href='https://atomgit.com/fenju/open-atom-contributor-leaderboard/issues'>https://atomgit.com/fenju/open-atom-contributor-leaderboard/issues</a> 填写活动链接（必填）、贡献者/项目（选填）信息。
					</li>
				</ul>
			</Modal>
			<Paragraph style={{fontSize: 16}}>本榜单对2024年参与开放原子开源基金会及旗下项目开源活动的项目以及贡献者进行了数据统计<Paragraph type='secondary'>最近更新于：2024年6月14日</Paragraph></Paragraph>
			<Input
				placeholder={activeTab === '1' ? "搜索项目" : "搜索贡献者"}
				value={searchText}
				onChange={(e) => setSearchText(e.target.value)}
			/>
			<Tabs defaultActiveKey={activeTab} onChange={(key) => setActiveTab(key)}>
				<TabPane tab="项目" key="1">
					<Table dataSource={filteredProjectRanking} columns={projectColumns} />
				</TabPane>
				<TabPane tab="贡献者" key="2">
					<Table dataSource={filteredContributorRanking} columns={contributorColumns} />
				</TabPane>
			</Tabs>
			<Modal
				title="详细信息"
				open={currentInfo !== null}
				onCancel={() => setCurrentInfo(null)}
				footer={null}
			>
				{currentInfo ?
				<div>
					<p>{currentInfo.category === '贡献者' ? '姓名：' : '项目名：'}{currentInfo.name}</p>
					<p>贡献积分：{currentInfo.score}</p>
					<p>最新活动：{currentInfo.desc}</p>
					<p>活动列表：</p>
					<ul>
						{currentInfo.actions.map((action, i) => (
							<li key={currentInfo.name + action.time + i}>
								{action.time}，{action.name}：{action.theme}
							</li>
						))}
					</ul>
				</div> : null}
			</Modal>
		</Flex>
	);
}

export default App;
